<template>
  <div class="table-wrap" v-loading="loading">
    <div class="search_header">
      <div class="search_header_left">
        <el-button
          icon="el-icon-plus"
          @click="addProject"
          v-has="'enterpriseEconomic:add'"
          >新增企业</el-button
        >
        <el-button
          @click="downloadFile"
          v-has="'enterpriseEconomic:export'"
          >下载数据</el-button
        >
        <!-- <el-button
          icon="el-icon-back"
          @click="downloadFile"
          v-has="'enterpriseEconomic:import'"
          >导入数据</el-button
        >
        <el-button
          @click="downloadFile"
          v-has="'enterpriseEconomic:export'"
          >数据模版下载</el-button
        > -->
      </div>

      <div class="search_header_right">
        <el-input
          placeholder="请输入企业名称"
          v-model="parameter.name"
          @keydown.enter.native="search"
          clearable
          @clear="search"
        >
          <span
            @click="search"
            slot="suffix"
            style="display: inline-block"
          >
            <Icon
              title="搜索"
              name="sousuo"
              color="#A7ADB5"
              font-size="20"
            />
          </span>
        </el-input>
        <!-- <el-select
          placeholder="请选择"
          v-model="currentSelect"
          clearable
          @change="changeYearMonth"
        >
          <el-option
            v-for="item in enterpriseYearMonthOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select> -->
        <el-date-picker
          v-model="currentSelect"
          type="month"
          @change="changeYearMonth"
          clearable
          placeholder="选择月"
          @clear="search"
        >
        </el-date-picker>
        <el-select
          placeholder="是否规上企业"
          v-model="parameter.enterpriseFlag"
          clearable
          @change="search"
          @clear="search"
        >
          <el-option
            v-for="item in isScaleEnterpriseOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <el-table
      :data="projectList"
      :header-cell-style="{
        background: '#F2F6FB',
        color: ' #6B767D'
      }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        label="序号"
        align="center"
        show-overflow-tooltip
        width="80"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="年度"
        prop="year"
        width="80"
        show-overflow-tooltip
      />
      <el-table-column
        label="月度"
        prop="month"
        width="50"
        show-overflow-tooltip
      />
      <el-table-column
        label="企业名称"
        prop="name"
        width="300"
        show-overflow-tooltip
      />
      <el-table-column
        label="类型"
        prop="type"
        show-overflow-tooltip
      />
      <el-table-column
        label="累计营收(万元)"
        prop="revenue"
        show-overflow-tooltip
      />
      <el-table-column
        label="累计产值(万元)"
        prop="industryValue"
        show-overflow-tooltip
      />
      <el-table-column
        label="累计全口径税收(万元)"
        prop="tax"
        width="120"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        label="固投是否为工业投资"
        prop="industryFlag"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="本月完成FDI(万美元)"
        prop="finishValueTotal"
        show-overflow-tooltip
      />
      <el-table-column
        label="是否规上企业"
        prop="enterpriseFlag"
        show-overflow-tooltip
      />
      <el-table-column
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        show-overflow-tooltip
        width="150"
        v-if="!isBefore"
      >
        <template slot-scope="scope">
          <el-button
            @click="editProject(scope.row)"
            type="text"
            style="color: #00baff; font-weight: 400"
            v-has="'enterpriseEconomic:edit'"
            >编辑</el-button
          >
          <el-button
            @click="deleteProject(scope.row)"
            type="text"
            style="color: #ff5b5b; font-weight: 400"
            v-has="'enterpriseEconomic:delete'"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination" v-if="total">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="parameter.pageSize"
        @current-change="pageChange"
        :total="total"
        :current-page="parameter.pageIndex"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  enterpriseEconomicQuery,
  deleteEnterpriseEconomic,
  downloadEnterpriseEconomic,
  enterpriseEconomicMonthQuery
} from '@/api/dataManagement'
import Icon from '@/components/icon'
import {
  isScaleEnterpriseOptions,
  enterpriseYearMonthOptions
} from '@/utils/project/data'
import dayjs from 'dayjs'
import { downloadBlobFile } from '@/utils/download'
import listKeepAliveMixin from '@/mixins/listKeepAliveMixin'

export default {
  name: 'enterpriseEconomicList',
  mixins: [listKeepAliveMixin],
  components: {
    Icon
  },
  data() {
    return {
      projectList: [],
      total: '',
      parameter: {
        name: '',
        pageIndex: 1,
        pageSize: 10
      },
      loading: false,
      showDialog: false,
      currentSelect: '',
      isBefore: false
    }
  },
  computed: {
    isScaleEnterpriseOptions() {
      return isScaleEnterpriseOptions
    },
    enterpriseYearMonthOptions() {
      return enterpriseYearMonthOptions
    }
  },
  async mounted() {
    const res = await enterpriseEconomicMonthQuery()
    if (res.success) {
      this.currentSelect = dayjs(res.data).format('YYYY-M')
    }
    // const date = new Date()
    // this.currentSelect = dayjs(date).format('YYYY-M')
    const year = this.currentSelect.split('-')[0]
    const month = this.currentSelect.split('-')[1]
    this.parameter.year = year
    this.parameter.month = month
    this.getList()
  },
  activated() {
    if (this.$route.query.refresh) {
      this.getList()
      this.$router.replace({
        path: this.$route.path,
        query: { ...this.$route.query, refresh: undefined }
      })
    }
  },
  methods: {
    changeYearMonth() {
      this.parameter.pageIndex = 1
      if (this.currentSelect) {
        const select = dayjs(this.currentSelect).format(
          'YYYY-MM-DD'
        )
        const obj = this.getYearAndMonth(select)
        this.parameter.year = obj.year
        this.parameter.month = obj.month
      } else {
        this.parameter.year = ''
        this.parameter.month = ''
      }
      const selectedDate = dayjs(this.currentSelect)
      const lastMonth = dayjs().subtract(1, 'month')
      this.isBefore =
        selectedDate.isBefore(lastMonth, 'month') &&
        this.parameter.month !== '01'

      this.getList()
    },

    getYearAndMonth(dateStr) {
      const [year, month] = dateStr.split('-')
      return {
        year: year,
        month: month.startsWith('0')
          ? month.substring(1)
          : month
      }
    },

    search() {
      this.parameter.name =
        this.parameter.name?.trim?.() || ''
      this.parameter.pageIndex = 1
      this.getList()
    },

    pageChange(page) {
      this.parameter.pageIndex = page
      this.getList()
    },

    // 获取用户列表
    getList() {
      this.loading = true
      enterpriseEconomicQuery(this.parameter).then(
        (res) => {
          if (res.success) {
            this.total = res.data.count
            this.projectList = res.data.list
          }
          this.loading = false
        }
      )
    },

    // 表格高亮
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },

    addProject() {
      this.$router.push({
        path: '/dataManagement/enterpriseManagement/enterpriseEconomic/add',
        query: {
          title: '新增',
          isEdit: false
        }
      })
    },

    // 编辑
    editProject(row) {
      this.$router.push({
        path: '/dataManagement/enterpriseManagement/enterpriseEconomic/add',
        query: {
          pkid: row.pkid,
          data: row,
          title: '编辑',
          isEdit: true
        }
      })
    },

    // 删除项目
    deleteProject(row) {
      this.$confirm(
        '此操作将永久删除该企业，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteEnterpriseEconomic(row.pkid).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              if (
                this.total % 10 === 1 &&
                this.parameter.pageIndex ===
                  parseInt(this.total / 10) + 1 &&
                this.parameter.pageIndex !== 1
              ) {
                this.parameter.pageIndex -= 1
              }
              this.getList()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch((error) => {
          this.$message.info('已取消删除')
        })
    },
    downloadFile() {
      this.btnLoading = true
      downloadEnterpriseEconomic(this.parameter)
        .then((res) => {
          downloadBlobFile(res, '企业经济指标信息表.xlsx')
        })
        .catch((err) => {
          this.$message.error('下载失败')
        })
        .finally(() => {
          this.btnLoading = false
        })
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';
</style>
